<script setup>
import { computed, ref } from 'vue';
import FileIcon from '../../components/FileIcon.vue';
import { Icon } from '@iconify/vue';
import { useI18n } from 'vue-i18n';

const props = defineProps({
  groupId: { type: [String, Number], default: null },
  tabs: { type: Array, default: () => [] }, // [{ id, title, path?, dirty?, ext? }] 标签页数组
  activeId: { type: [String, Number], default: null },
  globalActiveId: { type: [String, Number], default: null },
});
const emit = defineEmits(['update:activeId', 'close', 'new', 'reorder', 'split', 'move', 'contextmenu', 'showDiff', 'hideDiff', 'rollbackFile']);

function setActive(id) { emit('update:activeId', id); }
function closeTab(id, e) { e?.stopPropagation?.(); emit('close', id); }

const hasTabs = computed(() => (props.tabs && props.tabs.length > 0));

const scrollRef = ref(null);
function onWheel(e) {
  const el = scrollRef.value;
  if (!el) return;
  const delta = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX;
  el.scrollLeft += delta;
}

const dragFromId = ref(null);
function onDragStart(e, id) {
  const tab = props.tabs.find(t => t.id === id);
  if (tab && (tab.id === 'settings' || tab.ext === 'settings')) {
    // 不允许拖拽设置标签页
    dragFromId.value = null;
    try { e.preventDefault(); } catch {}
    return;
  }
  dragFromId.value = id;
  try {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', String(id));
    e.dataTransfer.setData('application/json', JSON.stringify({ type: 'tabMove', fromGroupId: props.groupId, fromId: id }));
  } catch {}
}
function allowDrop(e) {
  try {
    if (e.dataTransfer) {
      const json = e.dataTransfer.getData('application/json');
      if (json) {
        const payload = JSON.parse(json);
        if (payload && payload.type === 'tabMove') {
          e.dataTransfer.dropEffect = 'move';
          e.preventDefault();
          return;
        }
      }
      e.dataTransfer.dropEffect = 'move';
    }
  } catch {}
  e.preventDefault();
}
function onDrop(e, targetId) {
  e.preventDefault();
  let from = null;
  try { from = e.dataTransfer.getData('text/plain'); } catch {}
  let external = null;
  try { const json = e.dataTransfer.getData('application/json'); if (json) external = JSON.parse(json); } catch {}
  if (!from) from = dragFromId.value;
  // 组间外部移动
  if (external && external.type === 'tabMove' && external.fromGroupId && external.fromId) {
    let after = false;
    try {
      const rect = e.currentTarget.getBoundingClientRect();
      after = e.clientX > (rect.left + rect.width / 2);
    } catch {}
    emit('move', { fromGroupId: external.fromGroupId, fromId: external.fromId, toGroupId: props.groupId, toId: targetId, after });
    dragFromId.value = null;
    return;
  }
  // 守护：只有当源是我们的标签页之一时才允许放置
  if (!props.tabs.some(t => String(t.id) === String(from))) {
    dragFromId.value = null;
    return;
  }
  // 不允许移动或定位特殊的设置标签页
  const fromTab = props.tabs.find(t => String(t.id) === String(from));
  const targetTab = props.tabs.find(t => String(t.id) === String(targetId));
  if ((fromTab && (fromTab.id === 'settings' || fromTab.ext === 'settings')) || (targetTab && (targetTab.id === 'settings' || targetTab.ext === 'settings'))) {
    dragFromId.value = null;
    return;
  }
  // 根据鼠标x位置确定放置位置：目标前/后
  let after = false;
  try {
    const rect = e.currentTarget.getBoundingClientRect();
    after = e.clientX > (rect.left + rect.width / 2);
  } catch {}
  if (from && from !== targetId) emit('reorder', { fromId: from, toId: targetId, after });
  dragFromId.value = null;
}

function onContainerDragOver(e) {
  // 允许在空白区域放置以追加
  allowDrop(e);
}

function onContainerDrop(e) {
  e.preventDefault();
  // 外部移动（跨组）
  let ext = null;
  try { const json = e.dataTransfer.getData('application/json'); if (json) ext = JSON.parse(json); } catch {}
  if (ext && ext.type === 'tabMove' && ext.fromGroupId && ext.fromId) {
    emit('move', { fromGroupId: ext.fromGroupId, fromId: ext.fromId, toGroupId: props.groupId, toId: null, after: true });
    dragFromId.value = null;
    return;
  }
  // 内部重排序：追加到末尾
  let from = null;
  try { from = e.dataTransfer.getData('text/plain'); } catch {}
  if (!from) from = dragFromId.value;
  if (!props.tabs.some(t => String(t.id) === String(from))) { dragFromId.value = null; return; }
  const lastId = props.tabs.length ? props.tabs[props.tabs.length - 1].id : null;
  if (lastId && from !== lastId) emit('reorder', { fromId: from, toId: lastId, after: true });
  dragFromId.value = null;
}
const { t } = useI18n();

// AI状态的上下文菜单
function onTabContextMenu(event, tab, groupId) {
  // 首先发出原始的上下文菜单事件
  emit('contextmenu', event, tab, groupId);
  
  // 如果标签页有AI状态，显示额外选项
  if (tab.aiStatus) {
    event.preventDefault();
    showAiContextMenu(event, tab, groupId);
  }
}

function showAiContextMenu(event, tab, groupId) {
  // 为AI操作创建上下文菜单
  const menu = document.createElement('div');
  menu.className = 'fixed z-50 bg-panel-bg border border-panel-border rounded-md shadow-lg py-1 min-w-[120px]';
  menu.style.left = event.clientX + 'px';
  menu.style.top = event.clientY + 'px';
  
  const items = [];
  
  if (tab.aiStatus.kind === 'modify' && tab.aiStatus.latestEntry?.beforeContent && tab.aiStatus.latestEntry?.afterContent) {
    items.push({
      label: tab.showingDiff ? 'Hide Diff' : 'Show Diff',
      action: () => {
        if (tab.showingDiff) {
          emit('hideDiff', groupId, tab);
        } else {
          emit('showDiff', groupId, tab);
        }
      }
    });
  }
  
  if (tab.aiStatus.latestEntry) {
    items.push({
      label: 'Rollback Changes',
      action: () => {
        emit('rollbackFile', tab.path, tab.aiStatus.latestEntry);
      }
    });
  }
  
  items.forEach((item, index) => {
    const menuItem = document.createElement('div');
    menuItem.className = 'px-3 py-1.5 text-sm cursor-pointer text-panel-fg hover:bg-subtle-bg';
    menuItem.textContent = item.label;
    menuItem.onclick = () => {
      item.action();
      document.body.removeChild(menu);
    };
    menu.appendChild(menuItem);
  });
  
  document.body.appendChild(menu);
  
  // 点击外部时移除菜单
  const removeMenu = (e) => {
    if (!menu.contains(e.target)) {
      document.body.removeChild(menu);
      document.removeEventListener('click', removeMenu);
    }
  };
  setTimeout(() => document.addEventListener('click', removeMenu), 0);
}
</script>

<template>
  <div class="h-9 flex items-stretch border-b border-panel-border bg-panel-bg/90 backdrop-blur">
    <div ref="scrollRef" @wheel.prevent="onWheel" @dragover="onContainerDragOver" @dragenter="onContainerDragOver" @drop="onContainerDrop" class="tabs-scroll flex-1 min-w-0 overflow-x-auto overflow-y-hidden flex items-stretch gap-px">
      <div v-for="t in tabs" :key="t.id"
           class="group flex items-center gap-1.5 px-3 text-[12px] select-none cursor-pointer transition-all duration-200 border-b-2"
           :class="[
             (t.id === (globalActiveId ?? activeId))
              ? 'text-panel-fg bg-accent/25 rounded mx-1 my-1 py-1 shadow-md font-medium border-accent'
              : 'text-muted-fg bg-panel-bg/90 hover:bg-subtle-bg hover:rounded mx-1 py-1 border-transparent',
             (dragFromId && dragFromId===t.id) ? 'opacity-70' : '',
             (t.aiStatus?.kind === 'delete') ? 'line-through opacity-60 bg-danger-bg/50' : ''
           ]"
           @click="setActive(t.id)"
           @auxclick.stop.prevent="($event.button===1) && closeTab(t.id, $event)"
           @contextmenu.stop.prevent="onTabContextMenu($event, t, groupId)"
            :draggable="!(t.id==='settings'||t.ext==='settings')"
           @dragstart="onDragStart($event, t.id)"
           @dragover.stop="allowDrop"
           @dragenter.stop="allowDrop"
           @drop.stop="onDrop($event, t.id)"
      >
        <span class="inline-block">
          <Icon v-if="t.id==='settings'||t.ext==='settings'" icon="codicon:gear" width="12" height="12" />
          <FileIcon v-else :name="t.title" :size="12" />
        </span>
        <span class="truncate">{{ t.title }}</span>
        <span v-if="t.preview" class="ml-1 inline-block text-muted-fg">(preview)</span>
        <span v-if="t.dirty" class="ml-1 inline-block h-1.5 w-1.5 rounded-full bg-warn-fg"></span>
        <!-- AI Status Indicators (keep only meaningful ones) -->
        <span v-if="t.aiStatus?.kind === 'delete'" class="ml-1 inline-block px-1 py-0.5 text-[9px] bg-danger-bg text-danger-fg rounded" title="File deleted by AI">DEL</span>
        <span v-else-if="t.aiStatus?.kind === 'create'" class="ml-1 inline-block px-1 py-0.5 text-[9px] bg-success-bg text-success-fg rounded" title="File created by AI">NEW</span>
        <button
          class="ml-1.5 inline-flex h-4 w-4 items-center justify-center rounded hover:bg-accent/20"
          :class="(t.id === (globalActiveId ?? activeId)) ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'"
          title="Close" @click.stop="closeTab(t.id, $event)">×</button>
      </div>
    </div>
    <div class="h-9 flex items-center px-1">
      <button
        class="action-button w-6 h-6 flex items-center justify-center rounded hover:bg-app-bg text-muted-strong"
        :class="!hasTabs ? 'opacity-40 cursor-not-allowed pointer-events-none' : ''"
        :disabled="!hasTabs"
        :title="t ? (t('app.split_editor')||'Split Editor') : 'Split Editor'"
        @click="hasTabs && $emit('split')"
      >
        <Icon icon="codicon:split-horizontal" width="16" height="16" />
      </button>
    </div>
  </div>
  
</template>
<style scoped>
.tabs-scroll { -ms-overflow-style: none; scrollbar-width: none; }
.tabs-scroll::-webkit-scrollbar { display: none; }
</style>


